#include <stdio.h>
#include <stdlib.h>
#include "arraylist.h"

void init_list(struct arraylist *p)
{
	p->num = 0; //开始数组元素个数为0
	printf("请输入动态数组的初始大小:");
	scanf("%d", &p->max_size);
	if (p->max_size <= 0)
	{
		p->data = malloc(sizeof(int) * MAX);
		p->max_size = MAX;
	}
	else
		p->data = malloc(sizeof(int) * (p->max_size));
}

void show(struct arraylist *p)
{
	if (p->num == 0)
	{
		fprintf(stderr, "数组中没有元素\n");
		return; //没有元素直接返回
	}
	printf("size = %d [", p->num);
	for (int i = 0; i < p->num; i++)
	{
		if (i != 0) //这种不用做减法运算,用这种
			putchar(',');
		printf("%d", p->data[i]);
		//	if (i != p->num - 1)
		//		putchar(',');
	}
	printf("]\n");
}

int is_empty(struct arraylist *p)
{
	return p->num == 0;
}

int get_member(struct arraylist *p, int num)
{
	if (num <= 0 || num > p->num)
	{
		fprintf(stderr, "输入的数不符合要求\n");
		return -1;
	}
	return p->data[num - 1];
}

void add(struct arraylist *p, int member)
{
	if (insert(p, p->num, member) == -1)
	{
		re_size(p);
		insert(p, p->num, member);
	}
}

int insert(struct arraylist *p, int num, int member)
{
	if (p->num == p->max_size)
		return -1;	     //数组满了，不能插入
	if (num < 0 || num > p->num) //插入位置不合理
		return -2;
	for (int i = p->num; i > num; --i)   //插入到第num个元素之后实际是插入到data[num]位置
		p->data[i] = p->data[i - 1]; //最后一个元素向后移动一位
	p->data[num] = member;
	++p->num;
	return 1;
}

int change(struct arraylist *p, int num, int new)
{
	if (num <= 0 || num > p->num) //范围在1~num之间
	{
		fprintf(stderr, "输入的数不符合要求");
		return -1;
	}
	int old = p->data[num - 1];
	p->data[num - 1] = new;
	return old;
}

int Delete(struct arraylist *p, int i)
{
	if (i < 1 || i > p->num)
		return -1;
	int old = p->data[i - 1];
	for (int j = i; j < p->num; j++)
		p->data[j - 1] = p->data[j];
	p->num--;

	return old; //返回被删除的元素
}

int search(struct arraylist *p, int value)
{
	for (int i = 0; i < p->num; i++)
		if (p->data[i] == value)
			return i;

	return -1; //没有找到返回-1
}

void clear(struct arraylist *p)
{
	p->num = 0; //直接让数组实际存在的元素个数变为0
	free(p->data);
	p->data = NULL;
}

void re_size(struct arraylist *p)
{
	//新容量设为旧容量的1.5倍
	int new_size = p->max_size + (p->max_size >> 1); //()保证先算位运算
	int *new_array = calloc(new_size, sizeof(int));
	for (int i = 0; i < p->max_size; i++)
		new_array[i] = p->data[i];
	free(p->data);
	p->data = new_array;
	// printf("%d扩容为%d\n",p->max_size,new_size);
	p->max_size = new_size; //修改数组最大容量
}